<?php
/**
 * @name 消息服务
 * @Author : yu
 * @Created : 2016-11-10
 * @Copyright : MPE.Fiidee.Monda.Cn
 */
namespace message\service;

use herosphp\bean\Beans;
use herosphp\core\Loader;
use herosphp\utils\Page;
use utils\x1\MyFunction;
use herosphp\cache\CacheFactory;
use herosphp\core\WebApplication;
use models\MessageModel;

Loader::import('utils.x1.MyFunction');

class MessageService extends CommonService
{
    private $thisModel = null;
    private static $__cacheCtrl;

    public function __construct($model)
    {
        parent::__construct($model);
        $this->thisModel = Loader::model('message');
        if (self::$__cacheCtrl == null) {
            $config = WebApplication::getInstance()->getConfigs();
            $cachetype = $config['cache_type'];

            self::$__cacheCtrl = CacheFactory::create($cachetype);
        }

    }

    //消息模板
    private $message_tmpl_arr = array(
        //订单管理业务
        'order_create' => array(
            'type' => '订单管理',
            'name_zh' => '已下单',
            'tmpl_param' => 'member_name,order_no',
            'tmpl_content' => '尊敬的管理员，会员:{member_name}已下单，订单号：{order_no}，请及时处理！',//已下单
        ),
        'order_cancel' => array(
            'type' => '订单管理',
            'name_zh' => '已取消',
            'tmpl_param' => 'member_name,order_no',
            'tmpl_content' => '尊敬的管理员，会员:{member_name}对订单号：{order_no}进行了取消！',//已取消
        ),
        'order_pay' => array(
            'type' => '订单管理',
            'name_zh' => '已支付',
            'tmpl_param' => 'member_name,order_no',
            'tmpl_content' => '尊敬的管理员，会员:{member_name}对订单号：{order_no}进行了支付！',//已支付
        ),
        'order_confirmed_receipt' => array(
            'type' => '订单管理',
            'name_zh' => '已确认收货',
            'tmpl_param' => 'member_name,order_no',
            'tmpl_content' => '尊敬的管理员，会员:{member_name}对订单号：{order_no}进行了收货！',//已确认收货
        ),
        //会员管理业务
        'member_registered' => array(
            'type' => '会员管理',
            'name_zh' => '已注册',
            'tmpl_param' => 'member_name',
            'tmpl_content' => '尊敬的管理员，会员{member_name}已注册为本站会员，请查看信息并联系客户实名认证等操作！',//已注册
        ),
    );

    /**
     * 获取模板内容
     * @param $message_name
     * @return mixed
     */

    public function getMessageTmpl($message_name)
    {

        return $this->message_tmpl_arr[$message_name];

    }

    /**
     * 验证参数
     * @param $param 验证参数
     * @param $message_name 消息名
     */
    public function validateParam($param, $message_name)
    {
        $tmpl = $this->getMessageTmpl($message_name);

        if (!isset($tmpl['tmpl_param'])) {

            return false;
        }

        $paramArr = array();

        foreach ($param as $k => $v) {

            $paramArr[] = $k;
        }

        return ($tmpl['tmpl_param'] == join(',', $paramArr)) ? true : false;
    }


    /**
     * 用模板和数据来生成消息内容
     * @param $message_name
     * @param $data
     */
    public function getMessageContent($message_name, $data)
    {
        $tmpl = $this->getMessageTmpl($message_name);

        $tmplContent = $tmpl['tmpl_content'];

        $kArr = array();
        $vArr = array();

        foreach ($data as $k => $v) {

            $kArr[] = '{' . $k . '}';
            $vArr[] = $v;
        }

        return str_replace($kArr, $vArr, $tmplContent);

    }

    //站内信搜索
    public function search($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And message.app_id='" . appId() . "'";

        if ($search_arr['id']) {
            $whereSql .= " And message.id in " . $search_arr['id'];
        }
        if (in_array($search_arr['select_mix_option1'], array('member_no', 'tmpl_name'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'member_no':
                    $whereSql .= " And member.username Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
                case 'tmpl_name':
                    $whereSql .= " And message.tmpl_name_zh Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }

        if (($search_arr['start_time'] != '' || $search_arr['end_time'] != '') && in_array($search_arr['select_mix_option2'], array('sendtime'))) {
            switch ($search_arr['select_mix_option2']) {
                case 'sendtime':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(message.sendtime)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));
                    break;
            }
        }

        if ($search_arr['status'] != '' && $search_arr['status'] != 'all') {

            $whereSql .= " And message.status=" . $search_arr['status'];
        }
        $count_sql = "Select  count(*)
                From message
                Left Join member  On message.member_id=member.id
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select message.*,member.username As member_username
                From message
                Left Join member  On message.member_id=member.id
                Where 1 $whereSql
                Order By message.sendtime Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);

        $pageHandler = new Page($total, $pagesize, $page);

        $pageData = $pageHandler->getPageData(DEFAULT_PAGE_STYLE);

        return array("items" => $items, "pageData" => $pageData, "total" => $total);
    }

    /**
     * 添加消息
     * @param $member_id 消息触发者
     * @param $message_name 消息名
     * @param $data 消息数据
     */
    public function addMessage($member_id, $message_name, $data)
    {

        $memberService = Beans::get('member.member.service');
        $tmpl = $this->getMessageTmpl($message_name);

        $tmpl_name_zh = $tmpl['type'];

        if (!$this->validateParam($data, $message_name)) {

            return false;
        }

        $data['member_id'] = $member_id;
        $member = $memberService->getUsernameById($member_id);
        $data['username'] = $member['username'];
        $data['message_content'] = $this->getMessageContent($message_name, $data);
        $data['status'] = 0;
        $data['sendtime'] = myNow();
        $data['is_read'] = 0;
        $data['tmpl_name_zh'] = $tmpl_name_zh;

        $this->handleMessageArray(true);//刷新

        return $this->thisModel->add($data);

    }

    //状态
    public function getMessageStatusText($k = '__all')
    {
        $arr = array(
            '0' => '未处理',
            '1' => '已处理',
            '2' => '已忽略',

        );

        return $k == '__all' ? $arr : $arr[$k];
    }


    /**
     * 获取未处理消息
     * @param bool $refresh 是否刷新缓存
     */
    public function handleMessageArray($refresh = false)
    {
        $messageModel = Loader::model('message');

        $cache = self::$__cacheCtrl->baseKey('admin')->ftype('message')->factor('um_' . appId());//UnHandledMessage
        $result = $cache->get();
        if (!$result || $refresh) {
            $items = $messageModel->getItems(array('status' => MessageModel::STATUS_UN_HANDLED), null, 'sendtime DESC', array(1, 4));
            $counts = $messageModel->count(array('status' => MessageModel::STATUS_UN_HANDLED));

            $result = array('counts' => $counts, 'items' => $items);
            $cache->set(null, $result);
        }
        return $result;
    }


}

